﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ProjectManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Project
{
    /// <summary>
    /// 项目主表操作类
    /// </summary>
    public class Project_MainHandle
    {
        private readonly SJDBContext _context;

        public Project_MainHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(ProjectMain entity)
        {
            try
            {
                _context.ProjectMains.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(ProjectMain entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新特定内容
        /// </summary>
        /// <param name="entityExt"></param>
        /// <returns></returns>
        public async Task<bool> UpdateProjectSpecificContentAsync(ProjectMainUpdateModelExtend entityExt)
        {
            try
            {
                ProjectMain entity = entityExt.ExtMapToEntity<ProjectMain, ProjectMainUpdateModelExtend>();
                _context.Attach(entity);
                foreach (var property in entityExt.UpdateProperties)
                {
                    _context.Entry(entity).Property(property).IsModified = true;
                }
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>UpdateProjectSpecificContentAsync", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(ProjectMain entity)
        {
            try
            {
                _context.ProjectMains.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.ProjectMains.Find(id);
                if (entity != null)
                {
                    _context.ProjectMains.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据文件id删除项目文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteProjectDocByObjectIdAsync(string objectId)
        {
            try
            {
                var entity = _context.ProjectDocuments.Where(d => d.ObjectId == objectId).FirstOrDefaultAsync().Result;
                if (entity != null)
                {
                    _context.ProjectDocuments.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>DeleteProjectDocByObjectIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ProjectMain> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.ProjectMains.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>GetEntityById", ex);
            }
            return null;
        }

        /// <summary>
        /// 获取项目详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ProjectMainExtend> GetDetailByIdAsync(string id)
        {
            try
            {
                ProjectMain entity = await _context.ProjectMains.FindAsync(id);
                ProjectMainExtend extend = null;
                if (entity != null)
                {
                    extend = entity.MapToExt<ProjectMain, ProjectMainExtend>();
                }
                return extend;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>GetDetailByIdAsync", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页获取所有项目
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<ProjectMain> projects, int count)> GetAllAsync(int pageNumber, int pageSize, Expression<Func<ProjectMain, bool>> condition = null)
        {
            try
            {
                var query = _context.ProjectMains.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                //总条数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.OrderByDescending(order => order.AddTime).Skip(skip).Take(pageSize);//倒序排列

                // 执行查询并返回结果
                var projects = await query.ToListAsync();
                //List<ProjectMainExtend> projects = new List<ProjectMainExtend>();
                //if (projectList != null && projectList.Count > 0)
                //{
                //    projects = projectList.MapToList<ProjectMain, ProjectMainExtend>();
                //}
                return (projects, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>GetAllAsync  page", ex);
            }
            return (null, 0);
        }

        /// <summary>
        /// 获取创建人的某个状态下的所有项目
        /// </summary>
        /// <param name="status"></param>
        /// <param name="addUserId"></param>
        /// <returns></returns>
        public async Task<List<ProjectMain>> GetAllProjectByCreateUserAsync(int status, string addUserId)
        {
            try
            {
                var query = _context.ProjectMains.AsQueryable();
                query = query.Where(p => p.Status.Equals(status) && p.AddUserId == addUserId);

                // 执行查询并返回结果
                var projects = await query.ToListAsync();
                return projects;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_MainHandle=>GetAllAsync  page", ex);
            }
            return null;
        }
    }
}
